<template>
  <div class="add-photos-dialog">
    <el-dialog
      v-model="visible"
      title="添加照片到相册"
      width="80%"
      top="5vh"
      :close-on-click-modal="false"
      @close="handleClose"
    >
      <div class="dialog-content">
        <!-- 搜索和筛选栏 -->
        <div class="search-bar">
          <el-input
            v-model="searchQuery"
            placeholder="搜索照片..."
            @input="handleSearch"
            clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          
          <el-select
            v-model="sortBy"
            placeholder="排序方式"
            @change="handleSortChange"
            style="width: 120px; margin-left: 12px;"
          >
            <el-option label="拍摄时间" value="capturedAt" />
            <el-option label="创建时间" value="createdAt" />
            <el-option label="文件名" value="fileName" />
          </el-select>
          
          <el-select
            v-model="sortOrder"
            placeholder="排序顺序"
            @change="handleSortOrderChange"
            style="width: 100px; margin-left: 8px;"
          >
            <el-option label="降序" value="desc" />
            <el-option label="升序" value="asc" />
          </el-select>
        </div>
        
        <!-- 照片网格 -->
        <div class="photos-grid" v-loading="loading">
          <div
            v-for="photo in availablePhotos"
            :key="photo.id"
            class="photo-item"
            :class="{ selected: selectedPhotos.includes(photo.id) }"
            @click="togglePhotoSelection(photo.id)"
          >
            <img
              :src="getThumbnailUrl(photo)"
              :alt="photo.fileName"
              @error="handleImageError"
            />
            <div class="photo-overlay">
              <el-icon v-if="selectedPhotos.includes(photo.id)" class="check-icon">
                <Check />
              </el-icon>
            </div>
            <div class="photo-info">
              <div class="photo-name">{{ photo.fileName }}</div>
              <div class="photo-date">{{ formatDate(photo.capturedAt || photo.createdAt) }}</div>
            </div>
          </div>
        </div>
        
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            :page-size="pageSize"
            :total="total"
            layout="prev, pager, next, jumper, total"
            @current-change="handlePageChange"
          />
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button
            type="primary"
            @click="handleConfirm"
            :disabled="selectedPhotos.length === 0"
            :loading="submitting"
          >
            添加照片 ({{ selectedPhotos.length }})
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Search, Check } from '@element-plus/icons-vue';
import type { Photo } from '@/types';
import PhotoService from '@/services/photoService';

// 定义Props
const props = defineProps<{
  visible: boolean;
  albumId: number;
}>();

// 定义Emits
const emit = defineEmits<{
  'update:visible': [value: boolean];
  'added': [photoIds: number[]];
}>();

// 组件状态
const loading = ref(false);
const submitting = ref(false);
const searchQuery = ref('');
const sortBy = ref('capturedAt');
const sortOrder = ref('desc');
const currentPage = ref(1);
const pageSize = ref(40);
const total = ref(0);
const availablePhotos = ref<Photo[]>([]);
const selectedPhotos = ref<number[]>([]);

// 计算属性
const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
});

// 加载可用照片
const loadAvailablePhotos = async () => {
  loading.value = true;
  
  try {
    const result = await PhotoService.getPhotos({
      page: currentPage.value,
      pageSize: pageSize.value,
      query: searchQuery.value,
      sortBy: sortBy.value,
      sortOrder: sortOrder.value,
      excludeAlbumId: props.albumId // 排除已在相册中的照片
    });
    
    availablePhotos.value = result.photos;
    total.value = result.total;
  } catch (error) {
    console.error('加载照片失败:', error);
    ElMessage.error('加载照片失败');
  } finally {
    loading.value = false;
  }
};

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1;
  loadAvailablePhotos();
};

// 排序变更处理
const handleSortChange = () => {
  currentPage.value = 1;
  loadAvailablePhotos();
};

// 排序顺序变更处理
const handleSortOrderChange = () => {
  currentPage.value = 1;
  loadAvailablePhotos();
};

// 分页变更处理
const handlePageChange = (page: number) => {
  currentPage.value = page;
  loadAvailablePhotos();
};

// 切换照片选择状态
const togglePhotoSelection = (photoId: number) => {
  const index = selectedPhotos.value.indexOf(photoId);
  if (index > -1) {
    selectedPhotos.value.splice(index, 1);
  } else {
    selectedPhotos.value.push(photoId);
  }
};

// 确认添加照片
const handleConfirm = async () => {
  if (selectedPhotos.value.length === 0) {
    ElMessage.warning('请选择要添加的照片');
    return;
  }
  
  submitting.value = true;
  
  try {
    // 这里应该调用添加照片到相册的API
    // 暂时使用模拟数据
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    ElMessage.success(`已添加 ${selectedPhotos.value.length} 张照片到相册`);
    emit('added', selectedPhotos.value);
    handleClose();
  } catch (error) {
    console.error('添加照片失败:', error);
    ElMessage.error('添加照片失败');
  } finally {
    submitting.value = false;
  }
};

// 关闭对话框
const handleClose = () => {
  visible.value = false;
  selectedPhotos.value = [];
  searchQuery.value = '';
  currentPage.value = 1;
};

// 获取缩略图URL
const getThumbnailUrl = (photo: Photo) => {
  if (photo.thumbnailPath) {
    return `file://${photo.thumbnailPath}`;
  }
  return `file://${photo.filePath}`;
};

// 处理图片加载错误
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement;
  // 设置默认图片或错误处理
  img.src = '/path/to/default/image.jpg';
};

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return '未知';
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  });
};

// 监听对话框可见性变化
watch(visible, (newValue) => {
  if (newValue) {
    loadAvailablePhotos();
  }
});

// 生命周期
onMounted(() => {
  if (props.visible) {
    loadAvailablePhotos();
  }
});
</script>

<style scoped lang="scss">
.add-photos-dialog {
  .dialog-content {
    display: flex;
    flex-direction: column;
    height: 70vh;
    
    .search-bar {
      display: flex;
      align-items: center;
      margin-bottom: 16px;
    }
    
    .photos-grid {
      flex: 1;
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
      gap: 16px;
      overflow-y: auto;
      padding: 8px;
      border: 1px solid var(--el-border-color-light);
      border-radius: 4px;
      
      .photo-item {
        position: relative;
        aspect-ratio: 1;
        border-radius: 8px;
        overflow: hidden;
        cursor: pointer;
        transition: transform 0.2s, box-shadow 0.2s;
        border: 2px solid transparent;
        
        &:hover {
          transform: scale(1.03);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }
        
        &.selected {
          border-color: var(--el-color-primary);
        }
        
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
        
        .photo-overlay {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background-color: rgba(0, 0, 0, 0.3);
          display: flex;
          justify-content: center;
          align-items: center;
          opacity: 0;
          transition: opacity 0.2s;
          
          .check-icon {
            color: white;
            font-size: 24px;
          }
        }
        
        &.selected .photo-overlay {
          opacity: 1;
          background-color: rgba(var(--el-color-primary-rgb), 0.5);
        }
        
        .photo-info {
          position: absolute;
          bottom: 0;
          left: 0;
          right: 0;
          padding: 8px;
          background: linear-gradient(to top, rgba(0, 0, 0, 0.7), transparent);
          color: white;
          font-size: 12px;
          
          .photo-name {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
          
          .photo-date {
            opacity: 0.8;
            margin-top: 2px;
          }
        }
      }
    }
    
    .pagination-container {
      display: flex;
      justify-content: center;
      margin-top: 16px;
    }
  }
  
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .add-photos-dialog {
    .dialog-content {
      .search-bar {
        flex-direction: column;
        align-items: stretch;
        gap: 12px;
        
        .el-select {
          margin-left: 0 !important;
          width: 100% !important;
        }
      }
      
      .photos-grid {
        grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
        gap: 8px;
      }
    }
  }
}
</style>